package com.jochen.core.system

import com.artemis.Aspect
import com.badlogic.gdx.Gdx

import com.artemis.annotations.Wire
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.math.Matrix4
import com.badlogic.gdx.math.Vector2
import com.jochen.core.components.Sprite
import com.jochen.core.components.Transform
import com.jochen.core.system.abs.SortedIteratingSystem
import java.util.Comparator

class RendererSystem(): SortedIteratingSystem(Aspect.all(Sprite::class.java, Transform::class.java)) {

    @Wire private lateinit var batch: SpriteBatch
    @Wire private lateinit var camera: OrthographicCamera
    
    private var batchMatrix4: Matrix4? = null
    
    override fun sortEntities() {
        sortedEntities.sortWith(compareBy<Int> { entity ->
            Mapper.transforms.get(entity).z
        }.thenByDescending { entity ->
            Mapper.transforms.get(entity).position.y + Mapper.transforms.get(entity).sortOffsetY
        }.thenBy { entity ->
            Mapper.transforms.get(entity).position.x
        })
}
    
    override fun begin() {
        batchMatrix4 = batch.projectionMatrix
        batch.projectionMatrix = camera.combined
        batch.begin()
    }
    
    override fun end() {
        batch.end()
        batchMatrix4?.let { batch.projectionMatrix = it }
    }
    
    override fun process(entity: Int) {
        val transform = Mapper.transforms.get(entity)
        val sprite = Mapper.sprites.get(entity)
        
      //  sprite.region?: return
        if(sprite.region == null){
            Gdx.app.log("AAA","entity no region $entity")
            return
        }
        
        with(transform) {
            batch.color = sprite.color
            batch.draw(
                sprite.region,
                position.x - (1f - scaling.x) * size.x * 0.5f,//x,y
                position.y - (1f - scaling.y) * size.y * 0.5f,
                size.x * 0.5f, size.y * 0.5f,//origin
                size.x, size.y,//size
                scaling.x, scaling.y,//scalex
                rotationDeg
            )
        }
    }
}